import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication

from src.config_util import Config
from src.common import now_time, JenkinsUtil


class SendEmail:
    """ 发送邮箱 """

    def __init__(self, metrics):
        self.metrics = metrics
        self.conf = Config()
        self.email_conf = self.conf.get_conf(key="email_conf")
        self.jenkins_info = JenkinsUtil()

    def send(self, sub="【自动化测试结果通知】", is_html=True):
        """
        发送邮件
        @param sub: 邮件标题:
        @param is_html: 发送内容是否为html格式
        @return:
        """
        to = self.email_conf.get("to")
        user = f"<{self.email_conf.get('from')}>"
        if is_html:
            _subtype = "html"
        else:
            _subtype = "plain"
        message = MIMEText(self.init_content(), _subtype=_subtype, _charset='utf-8')
        message['Subject'] = sub
        message['From'] = user
        message['To'] = ";".join(to)
        server = smtplib.SMTP_SSL(self.email_conf.get("server_host"), port=465)
        server.connect(self.email_conf.get("server_host"), port=465)
        server.login(self.email_conf.get('from'), self.email_conf.get('pwd'))
        server.sendmail(user, to, message.as_string())
        server.close()

    def init_content(self):
        """定义邮件内容"""

        content = f"""
        <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>【自动化测试结果通知】</title>

</head>
<body style="padding-left: 30px;padding-top: 20px">
<div>

    <div class="head">
        <div>各位同事, 大家好:</div>
        <div style="margin-left: 25px">
            自动化用例执行完成，执行结果如下:
        </div>

    </div>
    <div class="body">
        <div class="test_info" style="margin-top: 30px">
            <div style="font-weight: 700">测试结果：</div>
            <hr>
            <ul style="padding: 0; margin: 0;">
                <li style="list-style-type: none;padding-top: 8px;">项目名称: {self.jenkins_info.job_name}</li>
                <li style="list-style-type: none;padding-top: 8px;">测试环境: {self.conf.get_conf('env')}</li>
                <li style="list-style-type: none;padding-top: 8px;">用例总数：{self.metrics.total}</li>
                <li style="list-style-type: none;padding-top: 8px;">成功用例数：{self.metrics.passed}</li>
                <li style="list-style-type: none;padding-top: 8px;">失败用例数：{self.metrics.failed}</li>
                <li style="list-style-type: none;padding-top: 8px;">异常用例数：{self.metrics.error}</li>
                <li style="list-style-type: none;padding-top: 8px;">跳过用例数：{self.metrics.skipped}</li>
                <li style="list-style-type: none;padding-top: 8px;">通过率：{self.metrics.pass_rate}%</li>
                <li style="list-style-type: none;padding-top: 8px;">失败用例：
                    <div style="margin-left: 30px">
                        {self.metrics.failed_cases}
                    </div>
                </li>
                <li style="list-style-type: none;padding-top: 8px;">执行总耗时：{self.metrics.duration}</li>
                <li style="list-style-type: none;padding-top: 8px;">通知时间：{now_time()}</li>
                <li style="list-style-type: none;padding-top: 8px;">测试报告：
                    <a style="text-decoration: none;" href="{self.jenkins_info.allure_url}">测试报告</a>
                </li>
            </ul>
        </div>
        <div class="build_info" style="margin-top: 30px">
            <div style="font-weight: 700">构建信息：</div>
            <hr>
            <ul style="padding: 0; margin: 0;">
                <li style="list-style-type: none;padding-top: 8px;">项目名称： {self.jenkins_info.job_name}</li>
                <li style="list-style-type: none;padding-top: 8px;">构建编号： 第{self.jenkins_info.build_number}次构建</li>
                <li style="list-style-type: none;padding-top: 8px;">构建日志：
                    <a style="text-decoration: none;" href="{self.jenkins_info.build_url}console">构建日志</a>
                </li>
                <li style="list-style-type: none;padding-top: 8px;">构建地址：
                    <a style="text-decoration: none;" href="{self.jenkins_info.build_url}">构建地址</a>
                </li>
            </ul>
        </div>

    </div>

</div>

</body>
</html>


        """
        return content


class Email(object):

    def __init__(self, ):
        self.email_conf = Config().get_conf(key="email_conf")

    def send(self, title, content=None, files_path_list=None):
        """
        发送邮件
        :param title: 邮件标题
        :param content: 邮件正文
        :param files_path_list: 附件地址绝对路径
        :return:
        """
        to = self.email_conf.get("to")
        user = f"<{self.email_conf.get('from')}>"
        message = MIMEMultipart()
        message.attach(MIMEText(content, _subtype="plain", _charset='utf-8'))
        message['Subject'] = title
        message['From'] = user
        message['To'] = ";".join(to)
        server = smtplib.SMTP_SSL(self.email_conf.get("server_host"), port=465)
        server.connect(self.email_conf.get("server_host"), port=465)
        if files_path_list:
            for file in files_path_list:
                filename = file.split('/')[-1]
                # 获取最新的email路径，如果存在说明有报错，构造附件，发送email路径下的excel文件
                att1 = MIMEApplication(open(file, 'rb').read())
                att1['Content-Type'] = 'application/octet-stream'
                # 这里的filename可以任意写，写什么邮件就显示什么名字
                att1.add_header('Content-Disposition', 'attachment', filename=filename)
                message.attach(att1)
        server.login(self.email_conf.get('from'), self.email_conf.get('pwd'))
        server.sendmail(user, to, message.as_string())
        server.close()


if __name__ == '__main__':
    SendEmail({}).send()
